package main

import (
	"context"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	lighthouse "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/lighthouse/v20200324"
)

var (
	zeroDialer net.Dialer
	httpClient = &http.Client{
		Timeout: 10 * time.Second,
	}
)

func init() {
	transport := http.DefaultTransport.(*http.Transport).Clone()
	transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
		return zeroDialer.DialContext(ctx, "tcp4", addr) // 指定本地网络类型,默认tcp是优先用ipv6,
	}
	httpClient.Transport = transport
}

func GetPublicIP() string {
	input_url := "https://ifconfig.co/ip"
	// response, err := http.Get(input_url)
	response, err := httpClient.Get(input_url)
	if err != nil {
		log.Fatal(err)
	}
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Fatal(err)
	}
	// fmt.Println(body)
	str := strings.Replace(string(body), "\n", "", -1)
	fmt.Println("本地公网IP地址: ", str)
	return str
}

func main3() {
	GetPublicIP()
}

func main() {
	// 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
	// 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
	// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
	credential := common.NewCredential(
		os.Getenv("TENCENTCLOUD_SECRET_ID"),
		os.Getenv("TENCENTCLOUD_SECRET_KEY"),
	)
	// 实例化一个client选项，可选的，没有特殊需求可以跳过
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "lighthouse.tencentcloudapi.com"
	// 实例化要请求产品的client对象,clientProfile是可选的
	client, _ := lighthouse.NewClient(credential, "ap-guangzhou", cpf)

	// 实例化一个请求对象,每个接口都会对应一个request对象
	request := lighthouse.NewModifyFirewallRulesRequest()

	request.InstanceId = common.StringPtr("lhins-4fsbz3j5")
	request.FirewallRules = []*lighthouse.FirewallRule{
		&lighthouse.FirewallRule{
			Protocol:                common.StringPtr("TCP"),
			Port:                    common.StringPtr("1-65535"),
			CidrBlock:               common.StringPtr(GetPublicIP()),
			Action:                  common.StringPtr("ACCEPT"),
			FirewallRuleDescription: common.StringPtr("家里网络"),
		},
	}

	// 返回的resp是一个ModifyFirewallRulesResponse的实例，与请求对象对应
	// 防火墙api中不支持ipv6的源地址
	response, err := client.ModifyFirewallRules(request)
	if _, ok := err.(*errors.TencentCloudSDKError); ok {
		fmt.Printf("An API error has returned: %s", err)
		return
	}
	if err != nil {
		panic(err)
	}
	// 输出json格式的字符串回包
	fmt.Printf("%s", response.ToJsonString())
}
